package com.kxf.zxingmini.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

/**
 * @ProjectName: AndroidTestDemo
 * @Package: com.kxf.zxingmini.view
 * @ClassName: ViewFinderView
 * @Description: 查找二维码的动态View
 * @Author: kuangxuefeng
 * @qq: 1024883177
 * @CreateDate: 2021/3/24 16:36
 */
public class ViewFinderView extends View {
    private int heightIndex = 0;
    private Paint paint;
    private boolean active = true;

    public ViewFinderView(Context context) {
        super(context);
        init();
    }

    public ViewFinderView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ViewFinderView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public ViewFinderView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    private void init() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(getResources().getColor(android.R.color.white));
        paint.setStrokeWidth(10);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = canvas.getWidth();
        int height = canvas.getHeight();
        canvas.drawLine(30, heightIndex, width-30, heightIndex, paint);
        heightIndex+=30;
        if (heightIndex>=height){
            heightIndex = 0;
        }
        if (active){
            postInvalidateDelayed(80);
        }
    }

    //线是否需要动
    public void setActive(boolean active) {
        this.active = active;
        if (active){
            postInvalidateDelayed(80);
        }
    }
}
